from django import forms
from utils.BootStrap import BootStrapModelForm
from django.core.exceptions import ValidationError
from  web import models
from web.form.widgets import ColorRadio


class ProjectAddModelForm(BootStrapModelForm):
      BootStrap_exclude = ["color"]
      class Meta:
          model = models.Project
          fields = ["name","color","desc"]
          widgets = {
              "desc":forms.Textarea,
              "color":ColorRadio(attrs={'class': 'color-radio'}),
          }

      def __init__(self,request,*args,**kwargs):
          super().__init__(*args,**kwargs)
          self.request = request
      # 项目校验
      def clean_name(self):
          name = self.cleaned_data.get("name")
          # 1.当前用户是否已创建过同名的项目
          exist = models.Project.objects.filter(name=name,creator=self.request.transaction.user).exists()
          if exist:
              raise ValidationError("项目名已存在")
          # 2.判断额度是否足够
          count = models.Project.objects.filter(creator=self.request.transaction.user).count() # 当前用户多少个项目
          if count >= self.request.transaction.price_policy.project_num:
              raise ValidationError("项目数量超限，需购买套餐")
          return  name
